;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Purchase.AgentStorePlanCtrl", [])
        .controller("AgentStorePlanCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "UserContextService", "Upload", "$timeout", "EventBus", "$filter", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, UserContextService, Upload, $timeout, EventBus, $filter) {
            var btnPermissionCode = {
                purchasePlanAgentStoreAdd: window.ActionCode.purchasePlanAgentStoreAdd,
                purchasePlanAgentStoreImport: window.ActionCode.purchasePlanAgentStoreImport,
                purchasePlanAgentStoreEdit: window.ActionCode.purchasePlanAgentStoreEdit,
                purchasePlanAgentStoreDel: window.ActionCode.purchasePlanAgentStoreDel,
                purchasePlanAgentStoreAudit: window.ActionCode.purchasePlanAgentStoreAudit,
                purchasePlanAgentStoreExport: window.ActionCode.purchasePlanAgentStoreExport
            };

            $scope.btnPermission = {
                purchasePlanAgentStoreAdd: true,
                purchasePlanAgentStoreImport: true,
                purchasePlanAgentStoreEdit: true,
                purchasePlanAgentStoreDel: true,
                purchasePlanAgentStoreAudit: true,
                purchasePlanAgentStoreExport: true
            };

            var tabFlag = {
                0: "门店采购计划详情",
                1: "新增门店采购计划",
                2: "编辑门店采购计划"
            };

            $scope.auditEnum = {
                Pass: 0,
                NoPass: 1
            };

            $scope.statusEnum = {
                /*0:"草拟",
                1:"待审核",
                2:"审核通过",
                3:"返回修改",
                4:"已汇总",*/
                Draft: 0,
                ToBeAudited: 1,
                Passed: 2,
                BackEdit: 3,
                Summary: 4
            };

            $scope.urlTab = {
                addAndSave: "/agentPlan/storeSave",
                addAndCommit: "/agentPlan/storeCommit",
                editAndSave: "/agentPlan/updateSave",
                editAndCommit: "/agentPlan/updateCommit"
            };

            $scope.activeFlag = [true, false, false];
            $scope.datePickerFlag = [false, false];
            $scope.tabFlag = {};

            $scope.condition = {};
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                showMateriel: false
            };
            $scope.exportParam = {
                sectionParam: {ids: []},
                allUrl: ybHttp.RequestUrl("device", "/agentPlan/storeExport")
            };
            $scope.orderObj = {
                headerInfo: {},
                materialList: []
            };
            $scope.tableConfig = {
                fixedWidth: 150,
                scrollWidth: 1450,
                tableCol: [
                    {
                        type: "",
                        name: "计划单号",
                        dataField: "planNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "采购类型",
                        dataField: "typeDesc",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核状态",
                        dataField: "statusDesc",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "createName",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "汇总后单号",
                        dataField: "mergeNo",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核人",
                        dataField: "auditName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "note",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核时间",
                        dataField: "auditTimeShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortField: "status",
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "备注",
                        dataField: "remark",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 130,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.materielTableConfig = {
                scrollWidth: 780,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        needInput: false
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        needInput: false
                    },
                    {
                        name: "零件类型",
                        width: 150,
                        dataField: "materialsType",
                        needInput: false
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        needInput: false
                    },
                    {
                        name: "单价(￥)",
                        width: 120,
                        dataField: "price",
                        inputType: "price"
                    },
                    {
                        name: "数量",
                        width: 100,
                        dataField: "qty",
                        needInput: true,
                        inputType: "qty"
                    },
                    {
                        name: "总价(￥)",
                        width: 120,
                        dataField: "totalPrice",
                        needInput: false
                    }
                ]
            };
            $scope.viewTbConf = {
                scrollWidth: 1020,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        needInput: false
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialsDes",
                        needInput: false
                    },
                    {
                        name: "零件类型",
                        width: 150,
                        dataField: "materialsType",
                        needInput: false
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        needInput: false
                    },
                    {
                        name: "单价(￥)",
                        width: 120,
                        dataField: "price",
                        inputType: "price"
                    },
                    {
                        name: "数量",
                        width: 100,
                        dataField: "qty",
                        needInput: true,
                        inputType: "qty"
                    },
                    {
                        name: "总价(￥)",
                        width: 120,
                        dataField: "amount",
                        needInput: false
                    },
                    {
                        name: "调整后数量",
                        width: 100,
                        dataField: "adjustQty",
                        needInput: true,
                        inputType: "adjustQty"
                    },
                    {
                        name: "调整后总价(￥)",
                        width: 120,
                        dataField: "adjustAmount",
                        inputType: "adjustAmount"
                    },
                ]
            };
            $scope.markInfo = {
                allCheckedBill: false,
                allCheckedMaterial: false,
                curRow: -1
            };
            $scope.submitted = false;
            $scope.dataList = [];
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.detailInfo = {
                crucialDevice: 0,
                entranceDevice: 0
            };

            $scope.typeDescList = [
                {id: 1, name: "紧急"},
                {id: 2, name: "补库"},
                {id: 3, name: "月度"}
            ];

            $scope.statusList = [
                {id: $scope.statusEnum.Draft, name: "草拟"},
                {id: $scope.statusEnum.ToBeAudited, name: "待审核"},
                {id: $scope.statusEnum.Passed, name: "审核通过"},
                {id: $scope.statusEnum.BackEdit, name: "返回修改"},
                {id: $scope.statusEnum.Summary, name: "已汇总"}
            ];

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        getDataList();
                        $scope.submitted = false;
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    case 3:
                        break;
                    case 4:
                        break;
                    case 5:
                        break;
                    default:
                        break;
                }
            };

            $scope.addApply = function () {
                $scope.tabFlag.type = 1;
                $scope.tabFlag.name = tabFlag[1];
                $scope.changeTab(2);
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {};
            };

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {left: $scope.tableConfig.fixedWidth + "px"}
                };
            };

            $scope.selMateriel = function (e) {
                if (!!$scope.toolbarConfig.showMateriel) {
                    e.stopPropagation();
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig.showMateriel = true;
                        EventBus.Publish("getMaterial");
                    });
                }
            };

            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.orderObj.materialList.length; i < len; i++) {
                    if (!!$scope.orderObj.materialList[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.orderObj.materialList.length - 1; i >= 0; i--) {
                        if (!!$scope.orderObj.materialList[i].isChecked) {
                            $scope.orderObj.materialList.splice(i, 1);
                        }
                    }
                    if ($scope.orderObj.materialList.length === 0) {
                        $scope.markInfo.allCheckedMaterial = false;
                    }
                    EventBus.Publish("setMaterial");
                });
            };

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                getBillIds();
            };

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
                getBillIds();
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };

            $scope.delMateriel = function (item, index) {
                ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                    $scope.orderObj.materialList.splice(index, 1);
                    EventBus.Publish("setMaterial", item.materialsNo);
                });
            };

            $scope.countTotal = function (item) {
                item.priceErr = false;
                item.qtyErr = false;
                if (!item.price || parseFloat(item.price) <= 0) {
                    item.priceErr = true;
                    return;
                }
                if (!item.qty || parseFloat(item.qty) <= 0) {
                    item.qtyErr = true;
                    return;
                }
                item.totalPrice = $filter("decimalCover")(ybWidget.Times(item.qty, item.price), 2);
            };

            $scope.saveData = function (url, invalid) {
                if (!invalid) {
                    $scope.submitted = true;
                    return;
                }
                var listValid = true;
                var service = "device";
                var reqUrl = url;

                if (!$scope.orderObj.materialList || $scope.orderObj.materialList.length === 0) {
                    ybWidget.ShowToaster('error', '零件不可为空');
                    return;
                }


                for (var i = 0, len = $scope.orderObj.materialList.length; i < len; i++) {
                    $scope.orderObj.materialList[i].priceErr = false;
                    $scope.orderObj.materialList[i].qtyErr = false;
                    if (!$scope.orderObj.materialList[i].price || parseFloat($scope.orderObj.materialList[i].price) <= 0) {
                        $scope.orderObj.materialList[i].priceErr = true;
                        listValid = false;
                        break;
                    }
                    if (!$scope.orderObj.materialList[i].qty || parseFloat($scope.orderObj.materialList[i].qty) <= 0) {
                        $scope.orderObj.materialList[i].qtyErr = true;
                        listValid = false;
                        break;
                    }
                }
                if (!listValid) {
                    return;
                }

                var param = angular.copy($scope.orderObj);
                param.detailList = $scope.orderObj.materialList;
                delete param.headerInfo.planType;

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            };

            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    default:
                        break;
                }
            };

            $scope.editApply = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.orderObj = data;
                    $scope.orderObj.headerInfo.planType = $scope.orderObj.headerInfo.planType === 0 ? "门店采购计划" : ($scope.orderObj.headerInfo.planType === 1 ? "'汇总采购计划'" : '-');
                    $scope.orderObj.materialList = $scope.orderObj.detailList;
                    $scope.orderObj.materialList.forEach(function (item) {
                        $scope.countTotal(item)
                    });
                    $scope.tabFlag.type = 2;
                    $scope.tabFlag.name = tabFlag[2];
                    $scope.changeTab(4);
                });
            };

            $scope.delApply = function (item) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/agentPlan/delete";
                    ybHttp.Get(service, reqUrl, {id: item.id}).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        $scope.search();
                    });
                })
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            function initData() {
                $scope.tabFlag = {};
                $scope.detailInfo = {
                    crucialDevice: 0,
                    entranceDevice: 0
                };
                $scope.orderObj = {
                    headerInfo: {},
                    materialList: []
                };
                $scope.markInfo.allCheckedMaterial = false;
                $scope.toolbarConfig.showMateriel = false;
                $scope.detailFlag = [true, true];
            }

            function getDataList(curPage) {
                $scope.markInfo = {
                    allCheckedBill: false,
                    allCheckedMaterial: false,
                    curRow: -1
                };
                $scope.exportParam.sectionParam.ids = [];
                var service = "device";
                var reqUrl = "/agentPlan/storeList";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.auditTimeShow = $filter("YbDate")(item.auditTime, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            function viewDetail(item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.orderObj = data;
                    $scope.orderObj.headerInfo.planType = $scope.orderObj.headerInfo.planType === 0 ? "门店采购计划" : ($scope.orderObj.headerInfo.planType === 1 ? "'汇总采购计划'" : '-');
                    $scope.orderObj.materialList = $scope.orderObj.detailList;
                    $scope.changeTab(3);
                });
            }

            function getDetail(item, type) {
                var param = {
                    id: item.id
                };
                return ybHttp.Get('device', '/agentPlan/item', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    return resp.value;
                });
            }

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.auditApply = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.orderObj = data;
                    $scope.orderObj.headerInfo.planType = $scope.orderObj.headerInfo.planType === 0 ? "门店采购计划" : ($scope.orderObj.headerInfo.planType === 1 ? "'汇总采购计划'" : '-');
                    $scope.orderObj.materialList = $scope.orderObj.detailList;

                    $scope.changeTab(5);
                });
            };

            $scope.auditFn = function (type) {
                $scope.submitted = true;
                var service = "device";
                var reqUrl = "/agentPlan/auditPass";
                if (type === $scope.auditEnum.NoPass) {
                    reqUrl = "/agentPlan/auditReturn";
                    if (!$scope.orderObj.headerInfo.returnAdvice) {
                        return;
                    }
                }
                var param = {};
                param.id = $scope.orderObj.headerInfo.id;
                param.returnAdvice = $scope.orderObj.headerInfo.returnAdvice;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        if(resp.code===1){
                            ybWidget.ShowMessage("仅总部人员可审核", MESG_TYPE.Error);
                        }else{
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        }
                        return;
                    }
                    $scope.changeTab(0);
                });
            };

            $scope.import = function () {
                var param = {
                    name: "门店采购计划",
                    templateReqService: "device",
                    templateReqUrl: "/agentPlan/storeExport",
                    importReqService: "device",
                    importReqUrl: "/agentPlan/import",
                    importErrorUrl: "",
                };
                ybWidget.ImportFile(param).then(function (data) {});
            };

            (function () {
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
    ;
})(window, window.angular);
